package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Resource(type = StringRedisTemplate.class)
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCoud(String phone, HttpSession session) {
        // 校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {


            return Result.fail("手机号格式不正确");
        }
        // 生成验证码
        String code = RandomUtil.randomNumbers(6);
        // 保存验证码
//        session.setAttribute("code", code);

//        保存在Redis中
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);

        // 发送验证码
        log.debug("向手机号{}发送验证码：{}", phone, code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
        // 验证码校验
//        String sessionCode = (String) session.getAttribute("code");

        // 从Redis获取
        String sessionCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (!code.equals(sessionCode)) {
            return Result.fail("验证码错误");
        }
//        User user  =  baseMapper.selectByPhone(phone);
        User user = query().eq("phone", phone).one();
        if (user == null) {
            // 创建用户
            user = new User();
            user.setPhone(phone);
            user.setNickName("user_" + RandomUtil.randomString(10));
            save(user);
        }
//        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        // 返回Token
        String token = UUID.randomUUID().toString(true);
        // 将用户保存到Redis
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // 解决java.lang.Long cannot be cast to java.lang.String

        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldValue, fieldName) -> fieldName.toString()));
        String kye = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(kye, userMap);
        stringRedisTemplate.expire(kye, 30, TimeUnit.MINUTES);
        stringRedisTemplate.delete(LOGIN_CODE_KEY + phone);
        return Result.ok(token);
    }

    @Override
    public Result logout(HttpServletRequest request) {
        String authorization = request.getHeader("authorization");
        // 删除redis
        stringRedisTemplate.delete(LOGIN_USER_KEY + authorization);
        return Result.ok();
    }
}
